<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Helpers\Map;
use App\Model\Area;
use App\Model\ImporterDealerRelation;

class DealerRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\Dealer";

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected function commonRules()
    {
        return [
            'name' => 'required',
            'tel' => 'required'
        ];
    }

    protected function appendCommonFillData()
    {
        if ($code = $this->request->input('area_code')){
            if( $area = Area::findByCode($code)){
                return [
                    'area_code' => $code,
                    'area_name' => $area->area_name
                ];
            }
        }
        return [];
    }

    protected function processRelationFilter($query, $key, $operator, $value)
    {
        if ($key == "importer.id") {
            if($operator == "="){
                $where = ' importer_id ='.$value;
            }elseif ($operator == "in") {
                $value = $value?$value:0;
                $value = explode(',',$value);
                $value = implode(',',$value);
                $where = ' importer_id in('.$value.')';
            }else{
                $where = ' importer_id '.$operator.' '.$value;
            }
            return $query->whereRaw('id in (select dealer_id from sys_importer_dealer_relation where '.$where.' and deleted_at is null)');
        }
        return $query;
    }


    protected function commonSave($model)
    {
        $m = new Map();
        $res = $m->getLocation($model->area_name.$model->detail);
        if ($res){
            $model->latitude = $res['lat'];
            $model->longitude = $res['lng'];
            $model->save();
        }

        if ($importer_id = $this->request->input('importer_id')){
            ImporterDealerRelation::firstOrCreate(['importer_id'=>$importer_id,'dealer_id'=>$model->id]);
        }
        return true;
    }


}